# -*- coding:utf-8 -*-
import os
import threading
import time

import pyautogui
from pynput.keyboard import Controller, Key, KeyCode
from common.data import DB
from utils.read_write_case import read_case
from utils.sendMsg import sendWinMsg


class RunBase:
    instance = None
    lock = threading.RLock()

    def __new__(cls, *args, **kwargs):
        if cls.instance:
            return cls.instance

        with cls.lock:
            cls.instance = object.__new__(cls)
            return cls.instance

    @classmethod
    def click(self, item):
        pyautogui.click(button=item["button"], x=item["position"]["x"], y=item["position"]["y"],
                        duration=item["duration"])

    @classmethod
    def doubleClick(self, item):
        pyautogui.doubleClick(button=item["button"], x=item["position"]["x"], y=item["position"]["y"],
                              duration=item["duration"])

    @classmethod
    def drag(self, item):
        # 鼠标点下去
        pyautogui.mouseDown(button=item["button"], x=item["position"]["x"], y=item["position"]["y"])
        # 移动到绝对定位的位置
        pyautogui.dragTo(button=item["button"], x=item["position"]["tox"], y=item["position"]["toy"],
                         duration=item["duration"])
        # 松开鼠标
        pyautogui.mouseUp(button=item["button"], x=item["position"]["tox"], y=item["position"]["toy"])


    @classmethod
    def press_normal_key(cls):
        control = Controller()
        control.press("l")

    @classmethod
    def press_special_key(cls):
        control = Controller()
        control.press(getattr(Key, "l"))

    def drag_rel(self):
        # 移动到离按下位置的相对位置
        pyautogui.dragRel()

    def mouseDown(self, button, position):
        pyautogui.mouseDown(button=button, x=position["x"], y=position["y"])

    def mouseUp(self, button, position):
        pyautogui.mouseUp(button=button, x=position["x"], y=position["y"])

    def dragRel(self, button, position):
        pyautogui.dragRel()
        pyautogui.dragTo()


def Run():
    # 读取case，写入DB中
    DB.caseData = read_case()

    index = 1
    for item in DB.caseData["cases"]:

        if hasattr(RunBase, item["action"]):
            try:
                if item["type"] == "mouse":
                    getattr(RunBase, "move")(item)
                else:
                    time.sleep(item["sleepTime"])

                getattr(RunBase, item["action"])(item)
                index += 1
            except Exception as e:
                sendWinMsg("运行提示", f"运行第{index}个步骤时，报错")
        else:
            sendWinMsg("运行提示", f"没有找到第{index}个步骤的执行动作")
            index += 1
    sendWinMsg("运行提示", f"运行结束")
